package com.abel.roommanager.realm;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.abel.roommanager.pojo.Role;
import com.abel.roommanager.pojo.User;
import com.abel.roommanager.service.UserService;

import lombok.Data;
@Data
public class UserRealm extends AuthorizingRealm{
	@Autowired
	private UserService userService;
	//授权的方法,从数据库中读取用户有哪些权限
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//		根据用户名查找它的角色
		String username=(String) principals.getPrimaryPrincipal();
		User user=userService.findUserRolesByUsername(username);
		Set<String> roles=new HashSet<>();
//		获取用户的角色
		List<Role> rList=user.getRoles();
		for (Role role : rList) {
			roles.add(role.getRname());
		}
		SimpleAuthorizationInfo info=new SimpleAuthorizationInfo(roles);
		return info;
	}
//登录身份认证 从数据中查询当前用户名密码
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//		获取用户提交的账号
		String username=(String) token.getPrincipal();
//		根据用户名从数据库中查找用户
	    User user=	userService.findUserByUserName(username);
	    if (user==null) {
			return null;
		}
	    SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(),getName());
		return info;
	}

}
